<template>
  <div class="csup">
    <input type="file" ref="inputer" class="choosefile" @change="handleFileChange($event)" accept="video/*" />
  </div>
</template>

<script>
  var myfiles
  import axios from 'axios'
  import { HOST, OSS_API_HOST } from '@/constants'

  export default {
    name: 'fileupload',
    props: ['uploadsucess'],
    data () {
      return {
        mloading: null,
        filePath: null,
        targetFile: null,
        file: '',
        previewImg: {data: ''},
        ossupUrl: 'https://renshe.oss-cn-beijing.aliyuncs.com/',
      }
    },
    methods: {
      handleFileChange (e) {
        let inputDOM = this.$refs.inputer
        this.targetFile = inputDOM
        // 通过DOM取文件数据

        // this.file = inputDOM.files[0];
        this.file = e.target.files[0]
        myfiles = e.target.files[0]
        window.wfiles = e.target.files[0]
        window.tests = '我是测试数据'
        console.log(this.file.name)

        this.errText = ''
        let size = Math.floor(this.file.size / 1024)

        // if (size > 1024 * 6) {
        //   // 这里可以加个文件大小控制
        //   alert('上传文件不要超过6M')
        //   this.$refs.inputer.value = ''
        //   return false
        // }
        var reader = new FileReader()
        reader.onload = (function (file) {
          return function (e) {
            // console.info(this.result); //这个就是base64的图标格式了
            window.base64Image = this.result
          }
        })(e.target.files[0])
        reader.readAsDataURL(e.target.files[0])

        // 触发这个组件对象的input事件
        // this.$emit('input', this.file);
        // 这里就可以获取到文件的名字了
        this.fileName = this.file.name

        // alert(this.fileName)
        // 这里加个回调也是可以的
        // this.onChange && this.onChange(this.file, inputDOM.value);
        this.upload()
      },
      ossSign () {//签名
        console.log('57size:' + this.file.size)
        let tempFile = this.file
        let that = this
        console.log('60size:' + tempFile.size)

//        that.request.get('employees/getOssConfig', {
        axios.get(OSS_API_HOST + 'oss/signature/youxiangche', {
          token: 'aa08769cdcb26674c6706093503ff0a3',
          cmloading: true
        }).then((res) => {
          console.log(res.data)

          console.log('64size:' + window.tests)
          console.log('65size:----:' + tempFile.size)
          that.ossUpload(res.data)
        }, error => {
          setTimeout(() => {
            loading.close()
          }, 1000)

        })

      },
      ossUpload (sign) {//上传到阿里云
        let that = this
        // console.log('size:75:' + temp.size)
        console.log('size:87:' + this.file)
        console.log('size:88:' + window.base64Image)
        // console.log('size:88:' + window.base64Image)
        // console.log('size:89:' + that.file.size)

        function base64ToBlob (urlData) {
          var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n)
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
          }
          return new Blob([u8arr], {type: mime})
        }

        var newfiles =this.file// base64ToBlob(window.base64Image)

        let fileOfBlob = newfiles
        console.log(fileOfBlob.size + 'MMMMMMMMMMMMMMMMM')

        console.log('*****************')
        console.log(newfiles)
        console.log(newfiles.size)
        console.log('*****************')
        let data = {
          'key': 'string',
          'name': 'string',
          'type': 'string',
          'vpath': 'string'
        }
        /* eslint-disable no-undef */
        const instance = axios.create({
          timeout: 100000,
          headers: {'Content-Type': 'multipart/form-data'}
        })
        var last = that.file.name.split('.').length
        //var chuo = new Date().getTime() + '.' + that.file.name.split('.')[1];
        //var chuo = new Date().getTime() + '.jpg'
        //获取文件的后缀名

        var lastIndex = that.file.name.lastIndexOf('.')
        var fileLength = that.file.name.length
        var extName = that.file.name.substring(lastIndex, fileLength)
        var randm = Math.ceil(Math.random() * 1000000) + ''
        var chuo = new Date().getTime() + randm + extName
        // alert(chuo)
        let param = new FormData()  // 创建form对象
        param.append('chunk', '0') // 添加form表单中其他数据
        param.append('OSSAccessKeyId', sign.data.accessid) // 添加form表单中其他数据
        param.append('policy', sign.data.policy) // 添加form表单中其他数据
        param.append('Signature', sign.data.signature) // 添加form表单中其他数据
        param.append('Expires', sign.data.expire) // 添加form表单中其他数据
        param.append('key', sign.data.dir + chuo) // 添加form表单中其他数据
        param.append('success_action_status', '200') // 添加form表单中其他数据
        param.append('success_action_statusText', 'ok') // 添加form表单中其他数据
        param.append('Access-Control-Allow-Origin', '*') // 添加form表单中其他数据
        param.append('file', fileOfBlob, chuo)  // 通过append向form对象添加数据
        console.log('.................')
        console.log('size:107：' + that.file.size) // FormData私有类对象，访问不到，可以通过get判断值是否传进去
        console.log('.................')

        // alert(chuo)
        // let config = {
        //   headers: {'Content-Type': 'multipart/form-data'}
        // }
        // 添加请求头
        // console.log(config);
        // axios.defaults.headers.post['Content-Type'] = 'multipart/form-data';
        instance.post(sign.data.host, param).then(response => {
          console.log(response)
          console.log('-----------------------------------')
          if (response.status == 200) {
            let rimg = {
              key: sign.data.dir + chuo,
              name: that.file.name
            }

            //保存文件-对接业务系统接口
            that.uploadFile(rimg);

            // that.$indicator.close()
            // that.$refs.inputer.value = '';
            // resolve(rimg);
          } else {
            // alert('sssssssssssssssss')
          }
        }, error => {
          console.log(JSON.stringify(error))

          setTimeout(() => {
            this.mloading.close()
          }, 1000)
        })

      },
      //保存图片
      uploadFile(img) {
        let that = this;
        axios.post(OSS_API_HOST + 'oss/file', img).then(res=> {
          this.$emit('uploadsucess', res.data)
          setTimeout(() => {
            this.mloading.close()
          }, 200)
        })
      },

      upload () {

        let that = this
        console.log('size:163:' + this.file.size)
        this.mloading = this.$loading({
          lock: true,
          text: '请稍后...',
          spinner: 'el-icon-loading',

        })

        console.log('189size:' + this.file.size)

        this.ossSign()

      }
    }
  }
</script>

<style lang="scss" scoped>
  .choosefile {
    font-size: 200px;
    opacity: 0;
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 99;
    top: 0;
    left: 0;
  }

</style>
